package com.zhaowu;

import com.google.gson.Gson;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpTest {
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    public static void main(String[] args) throws IOException {
        System.out.println(get("http://localhost:8080/get_string"));
        System.out.println(get("http://localhost:8080/grey?name=zhangsan"));
        PostParam postParam = new PostParam("zhangsan", "lisi");
        Gson gson = new Gson();
        String json = gson.toJson(postParam);
        System.out.println(json);
        System.out.println(postJsonBody("http://localhost:8080/postBody",json));
        Map<String, String> map = new HashMap<>();
        map.put("a", postParam.a);
        map.put("b", postParam.b);
        System.out.println(postParam("http://localhost:8080/post",map));
    }

    public static String get(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static String postJsonBody(String url,String json) throws IOException {
        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
    public static String postParam(String url, Map<String,String> map) throws IOException {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder formBody = new FormBody.Builder();
        if (map.size() > 0) {
            for (Map.Entry<String, String> m : map.entrySet()) {
                formBody.add(m.getKey(), m.getValue());
            }
        }
        RequestBody body = formBody.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}
